package com.kfzx.www.mycalendardemo;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

public class MonthFragment extends Fragment {
    private static final String TAG = "MonthFragment";

    private RecyclerView mRecyclerView;
    private List<DayBean> mBeanList = new ArrayList<>();
    private String dateString;
    private DateTime mDateTime;
    private View mView;
    private int firstDayInDayOfWeek;
    private int lastDayInMonth;
    private TextView mTextView;

    public static Fragment newInstance(String dateString) {
        MonthFragment monthFragment = new MonthFragment();
        Bundle bundle = new Bundle();
        bundle.putString("dateString", dateString);
        monthFragment.setArguments(bundle);
        return monthFragment;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dateString = getArguments().getString("dateString");
        mDateTime = new DateTime(dateString);

        mView = inflater.inflate(R.layout.fragment_month, container, false);

        mTextView = (TextView) mView.findViewById(R.id.year_month_day);
        mTextView.setText(dateString);

        initViews();

        return mView;

    }

    private void initViews() {
        mBeanList.clear();
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 7));
        mRecyclerView.setNestedScrollingEnabled(false);

        initMonthData();
        MonthAdapter monthAdapter = new MonthAdapter(getContext(), mBeanList);
        mRecyclerView.setAdapter(monthAdapter);

    }

    private void initMonthData() {
        firstDayInDayOfWeek = mDateTime.dayOfMonth().withMinimumValue().getDayOfWeek();
        lastDayInMonth = mDateTime.dayOfMonth().withMaximumValue().getDayOfMonth();
        firstDayInDayOfWeek %= 7;
        for (int i = 0; i < firstDayInDayOfWeek; i++) {
            mBeanList.add(new DayBean(0));
        }
        for (int i = 1; i <= lastDayInMonth; i++) {
            mBeanList.add(new DayBean(i));
        }
        for (int i = 0; i < 10; i++) {
            int randomNumber = (int) (Math.random() * 28);
            int meeting = (int) (Math.random() * 4);
            int attendance = (int) (Math.random() * 4);
            mBeanList.get(randomNumber).setAttendanceType(attendance);
            mBeanList.get(randomNumber).setMeetingType(meeting);
        }
    }
}
